/**
 * axios request lib
 *
 * @summary config axios request
 * @author Lucky
 *
 * Created at     : 2019-04-11 11:51:01 
 * Last modified  : 2019-04-11 19:20:22
 */


import axios from 'axios'
import qs from 'qs'

// create an axios instance
const service = axios.create({
  baseURL: '/',
  timeout: 5000
})

axios.defaults.retry = 4
axios.defaults.retryDelay = 1000

service.interceptors.request.use(config => {
  
  if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8') {
    config.data = qs.stringify(config.data)
  }
  return config
})

// handle the request timeout
service.interceptors.response.use(undefined, function axiosRetryInterceptor (err) {
  var config = err.config

  // if config does not exist or the retry options is not set, then reject the err
  if (!config || !config.retry) return Promise.reject(err)

  // set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0

  // check if it has maxed out the total number of retries
  if (config.__retryCount >= config.retry) {
    // reject with the error
    return Promise.reject(err)
  }

  // increase the retry count
  config.__retryCount += 1

  // create new promise to handle exponential backoff
  var backoff = new Promise(function(resolve) {
    setTimeout(function() {
      resolve()
    }, config.retryDelay || 1)
  })

  // return the promise in which recalls axios to retry the request
  return backoff.then(function() {
    return axios(config)
  })

})

export default service